package com.chookss.home.gallery;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.CityEntity;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.GalleryHotSearchEntity;
import com.chookss.home.entity.GallerySearchEntity;
import com.chookss.home.entity.KnowledgeEntity;
import com.chookss.home.gallery.adapter.GallerySearchHotAddressAdapter;
import com.chookss.home.gallery.adapter.GallerySearchHotPicAdapter;
import com.chookss.home.gallery.adapter.GallerySearchHotTagAdapter;
import com.chookss.home.gallery.adapter.GallerySearchListAddressAdapter;
import com.chookss.home.gallery.adapter.GallerySearchPicAdapter;
import com.chookss.home.gallery.adapter.GallerySearchTagAdapter;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.CityEvent;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.VideoNewCatesActivity;
import com.chookss.view.DrawableTextView;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GallerySearchActivity extends BaseAct {

    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.llvDelele)
    LinearLayout llvDelele;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    @BindView(R.id.flowLayoutHistory)
    FlowLayout flowLayoutHistory;
    @BindView(R.id.tvHot)
    TextView tvHot;
    @BindView(R.id.rvHotPic)
    RecyclerView rvHotPic;
    @BindView(R.id.tvHotTag)
    TextView tvHotTag;
    @BindView(R.id.rvHotTag)
    RecyclerView rvHotTag;
    @BindView(R.id.tvHotAddress)
    TextView tvHotAddress;
    @BindView(R.id.rvHotAddress)
    RecyclerView rvHotAddress;
    @BindView(R.id.tvPicName)
    TextView tvPicName;
    @BindView(R.id.tvPicNameMore)
    DrawableTextView tvPicNameMore;
    @BindView(R.id.llPicName)
    LinearLayout llPicName;
    @BindView(R.id.rvPics)
    RecyclerView rvPics;
    @BindView(R.id.tvTag)
    TextView tvTag;
    @BindView(R.id.tvTagMore)
    DrawableTextView tvTagMore;
    @BindView(R.id.llTag)
    LinearLayout llTag;
    @BindView(R.id.rvTag)
    RecyclerView rvTag;
    @BindView(R.id.rvAddress)
    RecyclerView rvAddress;
    @BindView(R.id.tvAddress)
    TextView tvAddress;
    @BindView(R.id.tvAddressListMore)
    DrawableTextView tvAddressListMore;
    @BindView(R.id.llListAddress)
    LinearLayout llListAddress;
    //    @BindView(R.id.llHotResult)
//    LinearLayout llHotResult;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    @BindView(R.id.llSearchDelete)
    LinearLayout llSearchDelete;
    @BindView(R.id.rvPicsSpace)
    View rvPicsSpace;
    @BindView(R.id.rvTagSpace)
    View rvTagSpace;
    @BindView(R.id.rvAddressSpace)
    View rvAddressSpace;
    @BindView(R.id.rvHotAddressSpace)
    View rvHotAddressSpace;
    private GallerySearchHotPicAdapter hotPicAdapter;
    private List<GalleryHotSearchEntity.ImageListBean> hotPicList = new ArrayList<>();
    private GallerySearchHotTagAdapter hotTAGAdapter;
    private List<GalleryHotSearchEntity.TagListBean> hotTagList = new ArrayList<>();
    private GallerySearchHotAddressAdapter hotAddressAdapter;
    private List<GalleryHotSearchEntity.CityListBean> hotAddressList = new ArrayList<>();
    private GallerySearchPicAdapter picAdapter;
    private List<GallerySearchEntity.ImageListBean.ListBean> picList = new ArrayList<>();
    private GallerySearchTagAdapter tagdapter;
    private List<GallerySearchEntity.TagListBean.ListBean> tagList = new ArrayList<>();
    private GallerySearchListAddressAdapter addressAdapter;
    private List<GallerySearchEntity.CityListBean.ListBean> addressList = new ArrayList<>();
    private String searchKeyWord = "";//搜索关键词
    private List<String> lists = new ArrayList<>();
    private FlowAdapter adapter;
    //筛选标签
    private String startTime = "", endTime = "", provides = "", orgCodes = "", catalogCodes = "", tagCodes = "", tagName = "", citys = "", provinces = "", fileTypes = "";
    private CustomDrawerPopupView drawerPopupView;
    private static int SOURSE = 8;//选员工所用标识
    private int directorySOURSE = 6;//目录标识
    private List<ContactEntity> cacheList = new ArrayList<>();//
    private List<CityEntity.ChildListBean> cityLists = new ArrayList<>();
    private List<KnowledgeEntity> videoFolderList = new ArrayList<>();//图库目录选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_gallery_search);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "1", "26");
        //热搜
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 4);
        rvHotPic.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(4, Utils.dip2px(this, 2), false);
        rvHotPic.addItemDecoration(gridSpacingItemDecoration);
        hotPicAdapter = new GallerySearchHotPicAdapter(R.layout.item_gallery, this, hotPicList, 0);
        rvHotPic.setAdapter(hotPicAdapter);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(this, 3);
        rvHotTag.setLayoutManager(gridLayoutManager2);
        GridSpacingItemDecoration gridSpacingItemDecoration2 = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        rvHotTag.addItemDecoration(gridSpacingItemDecoration2);
        hotTAGAdapter = new GallerySearchHotTagAdapter(R.layout.item_gallery_hot_search_tag, this, hotTagList, 0);
        rvHotTag.setAdapter(hotTAGAdapter);
        GridLayoutManager gridLayoutManager3 = new GridLayoutManager(this, 3);
        rvHotAddress.setLayoutManager(gridLayoutManager3);
        GridSpacingItemDecoration gridSpacingItemDecoration3 = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        rvHotAddress.addItemDecoration(gridSpacingItemDecoration3);
        hotAddressAdapter = new GallerySearchHotAddressAdapter(R.layout.item_gallery_hot_search_address, this, hotAddressList, 0);
        rvHotAddress.setAdapter(hotAddressAdapter);
        ((SimpleItemAnimator) rvHotPic.getItemAnimator()).setSupportsChangeAnimations(false);
        ((SimpleItemAnimator) rvHotTag.getItemAnimator()).setSupportsChangeAnimations(false);
        ((SimpleItemAnimator) rvHotAddress.getItemAnimator()).setSupportsChangeAnimations(false);
        //搜索结果
        GridLayoutManager gridLayoutManager11 = new GridLayoutManager(this, 4);
        rvPics.setLayoutManager(gridLayoutManager11);
        GridSpacingItemDecoration gridSpacingItemDecoration11 = new GridSpacingItemDecoration(4, Utils.dip2px(this, 2), false);
        rvPics.addItemDecoration(gridSpacingItemDecoration11);
        picAdapter = new GallerySearchPicAdapter(R.layout.item_gallery, this, picList, 0);
        rvPics.setAdapter(picAdapter);
        rvTag.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        tagdapter = new GallerySearchTagAdapter(R.layout.item_gallery_search_result_tag, this, tagList);
        rvTag.setAdapter(tagdapter);
        rvAddress.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        rvAddress.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 12), getResources().getColor(R.color.white)));
        addressAdapter = new GallerySearchListAddressAdapter(R.layout.item_gallery_search_result_address, this, addressList);
        rvAddress.setAdapter(addressAdapter);
        ((SimpleItemAnimator) rvPics.getItemAnimator()).setSupportsChangeAnimations(false);
        ((SimpleItemAnimator) rvTag.getItemAnimator()).setSupportsChangeAnimations(false);
        ((SimpleItemAnimator) rvAddress.getItemAnimator()).setSupportsChangeAnimations(false);
        //搜索控件
        String text = new ShareUtils().getString(this, Utils.getCacheName(this,StaticClass.GALLERY_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                lists.addAll(stringList);
            }
            if (lists.size() > 0) {
                // 设置 Adapter
                flowLayoutHistory.setVisibility(View.VISIBLE);
                adapter = new FlowAdapter(this, lists);
                flowLayoutHistory.setAdapter(adapter);
                llHistory.setVisibility(View.VISIBLE);
            } else {
                llHistory.setVisibility(View.GONE);
                flowLayoutHistory.setVisibility(View.GONE);
            }
        } else {
            llHistory.setVisibility(View.GONE);
            flowLayoutHistory.setVisibility(View.GONE);
        }
        drawerPopupView = new CustomDrawerPopupView(this, new CusTomDrawerPopupListener() {
            @Override
            public void onListItemClick(int position, String data) {
                if (position == 0) {
                    showDatePickDialog(startTime, 0);
                } else if (position == 1) {
                    showDatePickDialog(endTime, 1);
                } else if (position == 2) {
                    Intent intent = new Intent(GallerySearchActivity.this, ContactsLogChoiceActivity.class);
                    MyApp.contactEntityLogList.clear();
                    MyApp.contactEntityLogList.addAll(cacheList);
                    intent.putExtra("source", SOURSE + "");
                    startActivity(intent);
                } else if (position == 3) {
                    Intent intent = new Intent(GallerySearchActivity.this, VideoNewCatesActivity.class);
                    Bundle bundle = new Bundle();
                    //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
                    ArrayList bundlelist = new ArrayList();
                    bundlelist.add(videoFolderList);
                    bundle.putParcelableArrayList("videoFolderList", bundlelist);
                    intent.putExtras(bundle);
                    intent.putExtra("videoType", directorySOURSE + "");
                    startActivity(intent);
                } else if (position == 4) {
                    Intent intent = new Intent(GallerySearchActivity.this, GalleryMultipleChoiceLabelActivity.class);
                    intent.putExtra("tagName", tagName);
                    intent.putExtra("tagCodes", tagCodes);
                    startActivity(intent);
                } else if (position == 5) {
                    Intent intent = new Intent(GallerySearchActivity.this, GalleryChoiceCityActivity.class);
                    Bundle bundle = new Bundle();
                    //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
                    ArrayList bundlelist = new ArrayList();
                    bundlelist.add(cityLists);
                    bundle.putParcelableArrayList("cityLists", bundlelist);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else if (position == 6) {
                    startTime = "";
                    endTime = "";
                    provides = "";
                    catalogCodes = "";
                    tagCodes = "";
                    tagName = "";
                    citys = "";
                    fileTypes = "";
                    cacheList.clear();
                    cityLists.clear();
                } else if (position == 7) {
                    drawerPopupView.dismiss();
                    getSearchData();
                } else if (position == 8) {
                    fileTypes = data;
                }
            }
        });
        edContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(v.getText().toString());
                        searchKeyWord = v.getText().toString();
                        Utils.hideInputKeyboard(GallerySearchActivity.this, edContent);
                        getSearchData();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (edContent == null) {
                    return;
                }
                if (Utils.isNull(edContent.getText().toString())) {
                    llSearchDelete.setVisibility(View.GONE);
                } else {
                    llSearchDelete.setVisibility(View.VISIBLE);
                }

            }
        });
        getHotData();
    }

    private void getHotData() {
        showLoading();
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<GalleryHotSearchEntity>>() {
        }.getType(), null, Urls.selectAppHotSearchList, SignUtils2.makeSignStr(null), false, new ObserverCallback<GalleryHotSearchEntity>() {
            @Override
            public void onSuccess(GalleryHotSearchEntity data) {
                dismissLoading();
                if (data != null) {
                    hotPicList.clear();
                    hotTagList.clear();
                    hotAddressList.clear();
                    if (data.getCityList().size() == 0 && data.getImageList().size() == 0 && data.getTagList().size() == 0) {
                        llNone.setVisibility(View.VISIBLE);
                    } else {
                        llNone.setVisibility(View.GONE);
                        tvHot.setVisibility(View.VISIBLE);
                        rvHotPic.setVisibility(View.VISIBLE);
                        tvHotTag.setVisibility(View.VISIBLE);
                        rvHotTag.setVisibility(View.VISIBLE);
                        tvHotAddress.setVisibility(View.VISIBLE);
                        rvHotAddress.setVisibility(View.VISIBLE);
                        rvHotAddressSpace.setVisibility(View.VISIBLE);
                        if (data.getImageList().size() > 0) {
                            rvHotPic.setVisibility(View.VISIBLE);
                            tvHot.setVisibility(View.VISIBLE);
                            hotPicList.addAll(data.getImageList());
                            hotPicAdapter.notifyDataSetChanged();
                        } else {
                            rvHotPic.setVisibility(View.GONE);
                            tvHot.setVisibility(View.GONE);
                        }
                        if (data.getTagList().size() > 0) {
                            rvHotTag.setVisibility(View.VISIBLE);
                            tvHotTag.setVisibility(View.VISIBLE);
                            hotTagList.addAll(data.getTagList());
                            hotTAGAdapter.notifyDataSetChanged();
                        } else {
                            rvHotTag.setVisibility(View.GONE);
                            tvHotTag.setVisibility(View.GONE);
                        }
                        if (data.getCityList().size() > 0) {
                            rvHotAddress.setVisibility(View.VISIBLE);
                            tvHotAddress.setVisibility(View.VISIBLE);
                            hotAddressList.addAll(data.getCityList());
                            hotAddressAdapter.notifyDataSetChanged();
                        } else {
                            rvHotAddress.setVisibility(View.GONE);
                            tvHotAddress.setVisibility(View.GONE);
                        }
                    }
                } else {
                    llNone.setVisibility(View.VISIBLE);
                }


            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getSearchData() {
        showLoading();
        Map<String, String> allmap = new HashMap<>();
        if (!Utils.isNull(searchKeyWord)) {
            allmap.put("searchKeyWord", searchKeyWord);
        }
        if (!Utils.isNull(startTime)) {
            allmap.put("startTime", startTime);
        }
        if (!Utils.isNull(endTime)) {
            allmap.put("endTime", endTime);
        }
        if (!Utils.isNull(provides)) {
            allmap.put("provideEmployeeCodes", provides);
        }
        if (!Utils.isNull(orgCodes)) {
            allmap.put("orgCodes", orgCodes);
        }
        if (!Utils.isNull(catalogCodes)) {
            allmap.put("catalogCodes", catalogCodes);
        }
        if (!Utils.isNull(tagCodes)) {
            allmap.put("tagCodes", tagCodes);
        }
        if (!Utils.isNull(provinces)) {
            allmap.put("imageUploadLocationProvinces", provinces);
        }
        if (!Utils.isNull(citys)) {
            allmap.put("imageUploadLocationCitys", citys);
        }
        if (!Utils.isNull(fileTypes)) {
            allmap.put("fileTypes", fileTypes);
        }

        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<GallerySearchEntity>>() {
        }.getType(), null, Urls.selectAppImageSearchList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<GallerySearchEntity>() {
            @Override
            public void onSuccess(GallerySearchEntity data) {
                dismissLoading();
                llHistory.setVisibility(View.GONE);
                flowLayoutHistory.setVisibility(View.GONE);
                tvHot.setVisibility(View.GONE);
                rvHotPic.setVisibility(View.GONE);
                tvHotTag.setVisibility(View.GONE);
                rvHotTag.setVisibility(View.GONE);
                tvHotAddress.setVisibility(View.GONE);
                rvHotAddress.setVisibility(View.GONE);
                rvHotAddressSpace.setVisibility(View.GONE);
                if (data != null) {
                    picList.clear();
                    tagList.clear();
                    addressList.clear();
                    llNone.setVisibility(View.GONE);
                    if (data.getImageList() != null) {
                        if (data.getImageList().getList().size() > 0) {
                            rvPics.setVisibility(View.VISIBLE);
                            llPicName.setVisibility(View.VISIBLE);
                            rvPicsSpace.setVisibility(View.VISIBLE);
                            picList.addAll(data.getImageList().getList());
                            picAdapter.notifyDataSetChanged();
                            tvPicName.setText(data.getImageList().getTotal() + "张图片");
                            if (Utils.changeNumber(data.getImageList().getTotal()) > 4) {
                                tvPicNameMore.setVisibility(View.VISIBLE);
                            } else {
                                tvPicNameMore.setVisibility(View.GONE);
                            }
                        } else {
                            rvPics.setVisibility(View.GONE);
                            llPicName.setVisibility(View.GONE);
                            rvPicsSpace.setVisibility(View.GONE);
                        }
                    } else {
                        rvPics.setVisibility(View.GONE);
                        llPicName.setVisibility(View.GONE);
                        rvPicsSpace.setVisibility(View.GONE);
                    }
                    if (data.getTagList() != null) {
                        if (data.getTagList().getList().size() > 0) {
                            tagdapter.setSearchData(searchKeyWord, searchKeyWord, startTime, endTime, provides, orgCodes, catalogCodes, tagCodes, provinces, citys, fileTypes);
                            rvTag.setVisibility(View.VISIBLE);
                            llTag.setVisibility(View.VISIBLE);
                            rvTagSpace.setVisibility(View.VISIBLE);
                            tagList.addAll(data.getTagList().getList());
                            tagdapter.notifyDataSetChanged();
                            tvTag.setText(data.getTagList().getTotal() + "个标签");
                            if (Utils.changeNumber(data.getTagList().getTotal()) > 2) {
                                tvTagMore.setVisibility(View.VISIBLE);
                            } else {
                                tvTagMore.setVisibility(View.GONE);
                            }
                        } else {
                            rvTag.setVisibility(View.GONE);
                            llTag.setVisibility(View.GONE);
                            rvTagSpace.setVisibility(View.GONE);
                        }

                    } else {
                        rvTag.setVisibility(View.GONE);
                        llTag.setVisibility(View.GONE);
                        rvTagSpace.setVisibility(View.GONE);
                    }
                    if (data.getCityList() != null) {
                        if (data.getCityList().getList().size() > 0) {
                            addressAdapter.setSearchData(searchKeyWord, searchKeyWord, startTime, endTime, provides, orgCodes, catalogCodes, tagCodes, provinces, citys, fileTypes);
                            rvAddress.setVisibility(View.VISIBLE);
                            llListAddress.setVisibility(View.VISIBLE);
                            rvAddressSpace.setVisibility(View.VISIBLE);
                            addressList.addAll(data.getCityList().getList());
                            addressAdapter.notifyDataSetChanged();
                            tvAddress.setText(data.getCityList().getTotal() + "个地点");
                            if (Utils.changeNumber(data.getCityList().getTotal()) > 2) {
                                tvAddressListMore.setVisibility(View.VISIBLE);
                            } else {
                                tvAddressListMore.setVisibility(View.GONE);
                            }
                        } else {
                            rvAddress.setVisibility(View.GONE);
                            llListAddress.setVisibility(View.GONE);
                            rvAddressSpace.setVisibility(View.GONE);
                        }

                    } else {
                        rvAddress.setVisibility(View.GONE);
                        llListAddress.setVisibility(View.GONE);
                        rvAddressSpace.setVisibility(View.GONE);
                    }
                    if (tagList.size() == 0 && picList.size() == 0 && addressList.size() == 0) {
                        llNone.setVisibility(View.VISIBLE);
                    }

                } else {
                    llNone.setVisibility(View.VISIBLE);
                }


            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void add(String data) {
        // 设置 Adapter
        if (flowLayoutHistory == null) {
            return;
        }
        if (!lists.contains(data)) {
            if (lists.size() == 0) {
                lists.add(data);
            } else {
                lists.add(0, data);
            }

            saveSearchHistory();
            // 设置 Adapter
            llHistory.setVisibility(View.VISIBLE);
            flowLayoutHistory.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayoutHistory.setAdapter(adapter);
        }
    }

    private void saveSearchHistory() {
        if (lists.size() > 4) {
            lists.remove(0);
        }
        String text = JSON.toJSONString(lists);
        new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.GALLERY_HISTORY), text);
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_gallery_search_list, parent, false);
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            mlp.setMargins(0, 0, Utils.dip2px(mContext, 12), Utils.dip2px(mContext, 12));
            view.setLayoutParams(mlp);
            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchKeyWord = mContentList.get(position);
                    edContent.setText(searchKeyWord);
                    if (edContent != null) {
                        Utils.hideInputKeyboard(GallerySearchActivity.this, edContent);
                    }
                    getSearchData();
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.llSearchDelete, R.id.llvDelele, R.id.common_right_txt, R.id.tvPicNameMore, R.id.tvTagMore, R.id.tvAddressListMore})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llSearchDelete:
                edContent.setText("");
                searchKeyWord = "";
                llSearchDelete.setVisibility(View.GONE);
                break;
            case R.id.llvDelele:
                edContent.setText("");
                searchKeyWord = "";
                new ShareUtils().putString(this,Utils.getCacheName(this,StaticClass.GALLERY_HISTORY), "");
                llHistory.setVisibility(View.GONE);
                flowLayoutHistory.setVisibility(View.GONE);
                break;
            case R.id.common_right_txt:
                new XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .popupPosition(PopupPosition.Right)//右边
                        .offsetY(Utils.getStatusBarHeight(this))
                        .asCustom(drawerPopupView)
                        .show();
                break;
            case R.id.tvPicNameMore:
                intent = new Intent(this, GallerySearchPicListActivity.class);
                intent.putExtra("searchKeyWord", edContent.getText().toString());
                intent.putExtra("title", edContent.getText().toString());
                intent.putExtra("searchType", 1);
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                intent.putExtra("provides", provides);
                intent.putExtra("orgCodes", orgCodes);
                intent.putExtra("catalogCodes", catalogCodes);
                intent.putExtra("tagCodes", tagCodes);
                intent.putExtra("provinces", provinces);
                intent.putExtra("citys", citys);
                intent.putExtra("fileTypes", fileTypes);
                startActivity(intent);
                break;
            case R.id.tvTagMore:
                intent = new Intent(this, GallerySearchTagListActivity.class);
                intent.putExtra("searchKeyWord", edContent.getText().toString());
                intent.putExtra("title", edContent.getText().toString());
                intent.putExtra("searchType", 2);
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                intent.putExtra("provides", provides);
                intent.putExtra("orgCodes", orgCodes);
                intent.putExtra("catalogCodes", catalogCodes);
                intent.putExtra("tagCodes", tagCodes);
                intent.putExtra("provinces", provinces);
                intent.putExtra("citys", citys);
                intent.putExtra("fileTypes", fileTypes);
                startActivity(intent);
                break;
            case R.id.tvAddressListMore:
                intent = new Intent(this, GallerySearchAddressListActivity.class);
                intent.putExtra("searchType", 3);
                intent.putExtra("citys", edContent.getText().toString());
                intent.putExtra("searchKeyWord", edContent.getText().toString());
                intent.putExtra("title", edContent.getText().toString());
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                intent.putExtra("provides", provides);
                intent.putExtra("orgCodes", orgCodes);
                intent.putExtra("catalogCodes", catalogCodes);
                intent.putExtra("tagCodes", tagCodes);
                intent.putExtra("provinces", "");
                intent.putExtra("fileTypes", fileTypes);
                startActivity(intent);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("videoCate" + directorySOURSE)) {
                //目录选择
                catalogCodes = map.get("videoCate" + directorySOURSE);
                videoFolderList.clear();
                videoFolderList.addAll(MyApp.videoFolderList);
                MyApp.videoFolderList.clear();
                if (drawerPopupView != null) {
                    drawerPopupView.setData(3, map.get("videoNames"));
                }
            }
            if (map.containsKey("tagCodes")) {
                //标签选择
                tagCodes = map.get("tagCodes");
                tagName = map.get("tagName");
                if (drawerPopupView != null) {
                    drawerPopupView.setData(4, map.get("tagName"));
                }
            }
            if (map.containsKey("provinces")) {
                //地市选择
                provinces = map.get("provinces");
                citys = map.get("citys");
                if (drawerPopupView != null) {
                    if (Utils.isNull(provinces)) {
                        drawerPopupView.setData(5, citys);
                    } else {
                        if (Utils.isNull(citys)) {
                            drawerPopupView.setData(5, provinces);
                        } else {
                            drawerPopupView.setData(5, provinces + "," + citys);
                        }
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Web_Close")) {
                finish();
            } else if (msg.equals("Web_Cancel_dialog")) {
                dismissLoading();
            } else if (msg.equals("ChoiceContacts_Ok_" + SOURSE)) {
                //提供人选择
                if (drawerPopupView == null) {
                    return;
                }
                cacheList.clear();
                cacheList.addAll(MyApp.contactEntityLogList);
                String name = "";
                orgCodes = "";
                provides = "";
                for (int i = 0; i < cacheList.size(); i++) {
                    if (!cacheList.get(i).isHalfSelect()) {
                        if (Utils.isNull(name)) {
                            name = cacheList.get(i).getEmployeeName();
                        } else {
                            name = name + "," + cacheList.get(i).getEmployeeName();
                        }
                        if (cacheList.get(i).getType().equals("0")) {
                            if (Utils.isNull(orgCodes)) {
                                orgCodes = orgCodes + cacheList.get(i).getEmployeeCode();
                            } else {
                                orgCodes = orgCodes + "," + cacheList.get(i).getEmployeeCode();
                            }
                        } else {
                            if (Utils.isNull(provides)) {
                                provides = provides + cacheList.get(i).getEmployeeCode();
                            } else {
                                provides = provides + "," + cacheList.get(i).getEmployeeCode();
                            }
                        }

                    }
                }
                drawerPopupView.setData(2, name);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CityEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getList() != null) {
            cityLists.clear();
            cityLists = messageEvent.getList();
            provinces = "";
            citys = "";
            for (int i = 0; i < cityLists.size(); i++) {
                if (cityLists.get(i).getIndex() == 0) {
                    if (cityLists.get(i).getIndex_parent() == 0) {
                        provinces = cityLists.get(i).getName();
                    } else {
                        String province = cityLists.get(i).getName();
                        if (Utils.isNull(provinces)) {
                            provinces = provinces + province.substring(0, province.length() - 2);
                        } else {
                            provinces = provinces + "," + province.substring(0, province.length() - 2);
                        }
                    }

                } else {
                    if (Utils.isNull(citys)) {
                        citys = citys + cityLists.get(i).getName();
                    } else {
                        citys = citys + "," + cityLists.get(i).getName();
                    }
                }
            }
            if (drawerPopupView != null) {
                if (cityLists.size() == 1) {
                    if (cityLists.get(0).getIndex_parent() == 0) {
                        provinces = "";
                        drawerPopupView.setData(5, cityLists.get(0).getName());
                    } else {
                        if (Utils.isNull(provinces)) {
                            drawerPopupView.setData(5, citys);
                        } else {
                            if (Utils.isNull(citys)) {
                                drawerPopupView.setData(5, provinces);
                            } else {
                                drawerPopupView.setData(5, provinces + "," + citys);
                            }
                        }
                    }
                } else {
                    if (Utils.isNull(provinces)) {
                        drawerPopupView.setData(5, citys);
                    } else {
                        if (Utils.isNull(citys)) {
                            drawerPopupView.setData(5, provinces);
                        } else {
                            drawerPopupView.setData(5, provinces + "," + citys);
                        }
                    }
                }

            }
        }
    }

    private void showDatePickDialog(String curDate, int type) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        int year = 0, month = 0, day = 0;
        try {
            if (Utils.isNull(curDate)) {
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                year = Integer.parseInt(curDate.substring(0, curDate.indexOf("-")));
                month = Integer.parseInt(curDate.substring(curDate.indexOf("-") + 1,
                        curDate.lastIndexOf("-"))) - 1;
                day = Integer.parseInt(curDate.substring(curDate.lastIndexOf("-") + 1,
                        curDate.length()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
        }
        //构建一个日期对话框，该对话框已经集成了日期选择器
        //DatePickerDialog的第二个构造参数指定了日期监听器
        DatePickerDialog dialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String choiceMonth = "0", choiceDay = " 0";
                        if (month + 1 > 9) {
                            choiceMonth = (month + 1) + "";
                        } else {
                            choiceMonth = "0" + (month + 1);
                        }
                        if (dayOfMonth > 9) {
                            choiceDay = dayOfMonth + "";
                        } else {
                            choiceDay = "0" + dayOfMonth;
                        }
                        if (drawerPopupView == null) {
                            return;
                        }
                        if (type == 0) {
                            startTime = year + "-" + choiceMonth + "-" + choiceDay;
                            if (!Utils.isNull(endTime)) {
                                if (Utils.getTimeCompareSize(startTime,
                                        endTime) == 1) {
                                    MyToast.show("结束时间不能小于起始时间");
                                    startTime = "";
                                    drawerPopupView.setData(0, startTime);
                                } else {
                                    drawerPopupView.setData(0, startTime);
                                }
                            } else {
                                drawerPopupView.setData(0, startTime);
                            }
                        } else {
                            endTime = year + "-" + choiceMonth + "-" + choiceDay;
                            if (!Utils.isNull(startTime)) {
                                if (Utils.getTimeCompareSize(startTime,
                                        endTime) == 1) {
                                    MyToast.show("结束时间不能小于起始时间");
                                    endTime = "";
                                    drawerPopupView.setData(1, endTime);
                                } else {
                                    drawerPopupView.setData(1, endTime);
                                }
                            } else {
                                drawerPopupView.setData(1, endTime);
                            }
                        }

                    }
                },
                year,
                month,
                day);
        //把日期对话框显示在界面上
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApp.videoFolderList.clear();
        if (edContent != null) {
            Utils.hideInputKeyboard(GallerySearchActivity.this, edContent);
        }
    }
}
